import java.util.*;

/**
 * Created by zhourh on 2018/6/15.
 * 给定一个二叉树，返回其节点值自底向上的层次遍历。 （即按从叶子节点所在层到根节点所在的层，逐层从左向右遍历）

 例如：
 给定二叉树 [3,9,20,null,null,15,7],

 3
 / \
 9  20
 /  \
 15   7
 返回其自底向上的层次遍历为：

 [
 [15,7],
 [9,20],
 [3]
 ]

 bfs
 */
public class BinaryTreeLevelOrderTraversalII {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);

        System.out.println(new BinaryTreeLevelOrderTraversalII().levelOrderBottom(root));
    }

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        if (root == null) {
            return Collections.emptyList();
        }

        List<List<Integer>> result = new ArrayList<>();

        Queue<TreeNode> currentQueue = new LinkedList<>();
        Queue<TreeNode> nextQueue = new LinkedList<>();
        currentQueue.add(root);
        while (!currentQueue.isEmpty()) {
            List<Integer> levelResult = new ArrayList<>();
            // 将栈中的全部节点取出，重新放到一个队列中
            while (!currentQueue.isEmpty()) {
                TreeNode node = currentQueue.poll();
                levelResult.add(node.val);
                nextQueue.add(node);
            }

            result.add(levelResult);

            // 将队列中的所有节点的子节点放入栈中
            while (!nextQueue.isEmpty()) {
                TreeNode node = nextQueue.poll();
                if (node.left != null) {
                    currentQueue.add(node.left);
                }
                if (node.right != null) {
                    currentQueue.add(node.right);
                }
            }
        }

        Collections.reverse(result);
        return result;
    }

}
